package com.digua.base.view

import android.content.Context
import android.util.AttributeSet
import android.widget.RelativeLayout
import com.blankj.utilcode.util.ActivityUtils
import com.digua.base.R
import com.digua.base.databinding.ViewBarBinding

class BarView : RelativeLayout {
    private lateinit var ui: ViewBarBinding

    constructor(context: Context?) : super(context) {
        initUI(null)
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
        initUI(attrs)
    }

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        initUI(attrs)
    }

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) {
        initUI(attrs)
    }

    private fun initUI(attrs: AttributeSet?) {
        ui = ViewBarBinding.bind(inflate(context, R.layout.view_bar, this))
        ui.back.setOnClickListener {
            val activity = ActivityUtils.getActivityByContext(context)
            activity?.let {
                if (it.isFinishing || it.isDestroyed) return@setOnClickListener
                it.finish()
            }
        }
        attrs?.let {
            val ta = context.obtainStyledAttributes(it, R.styleable.BarView)
            ui.title.text = ta.getText(R.styleable.BarView_title)
            ui.back.visibility = if (ta.getBoolean(R.styleable.BarView_showBack, true)) VISIBLE else GONE
        }
    }

    fun getViewBar() = ui
}